<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <el-tag v-if="adminInfo.level" type="info" class="admin-tag">{{ adminInfo.label }}</el-tag>
    </div>

    <el-card>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="学号/教师工号">
          <el-input v-model="searchForm.usercode" placeholder="请输入学号/教师工号" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.fullName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="searchForm.userType" placeholder="请选择用户类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="学生" value="STUDENT" />
            <el-option label="教师" value="TEACHER" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="userList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="usercode" label="学号/教师工号" width="120" />
        <el-table-column prop="fullName" label="姓名" width="100" />
        <el-table-column label="用户类型/身份" width="150">
          <template #default="{ row }">
            <div>
              <el-tag :type="row.userType === 'STUDENT' ? 'success' : 'warning'">
                {{ row.userType === 'STUDENT' ? '学生' : '教师' }}
              </el-tag>
            </div>
            <div v-if="getAdminRole(row)" class="admin-role-tag">
              <el-tag type="danger" size="small">{{ getAdminRoleLabel(row) }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180" />
        
        <!-- 根据管理员级别显示不同的组织信息 -->
        <el-table-column prop="schoolName" label="学校" width="120" v-if="shouldShowColumn('SCHOOL')" />
        <el-table-column prop="departmentName" label="学院" width="120" v-if="shouldShowColumn('DEPARTMENT')" />
        <el-table-column prop="majorName" label="专业" width="120" v-if="shouldShowColumn('MAJOR')" />
        <el-table-column prop="className" label="班级" width="120" v-if="shouldShowColumn('CLASS')" />
        
        <el-table-column label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'">
              {{ row.isActive ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <!-- 角色按钮：只有超级管理员和校级管理员可以设置教师的管理员角色 -->
            <el-button
              v-if="canManageAdminRole(row)"
              type="warning"
              link
              @click="handleAdminRole(row)"
            >
              角色
            </el-button>
            
            <!-- 删除按钮：超级管理员可以删除所有用户，其他管理员只能删除比自己级别低的用户 -->
            <el-button
              v-if="canDeleteUser(row)"
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>



    <!-- 管理员角色设置对话框 -->
    <el-dialog
      title="设置管理员角色"
      v-model="adminRoleDialogVisible"
      width="500px"
    >
      <el-form
        ref="adminRoleFormRef"
        :model="adminRoleForm"
        label-width="120px"
      >
        <el-form-item label="教师姓名">
          <el-input v-model="adminRoleForm.fullName" disabled />
        </el-form-item>
        <el-form-item label="管理员角色" prop="adminRole">
          <el-select v-model="adminRoleForm.adminRole" style="width: 100%">
            <el-option label="无管理权限" value="" />
            <el-option label="班级管理员" value="CLASS_ADMIN" />
            <el-option label="系级管理员" value="MAJOR_ADMIN" />
            <el-option label="院级管理员" value="DEPARTMENT_ADMIN" v-if="isSchoolAdmin" />
            <el-option label="校级管理员" value="SCHOOL_ADMIN" v-if="isSchoolAdmin && isSuperAdmin" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="adminRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitAdminRole">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../../stores/user'
import request from '../../utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

const userStore = useUserStore()
const adminRoleFormRef = ref(null)

// 管理员信息
const adminInfo = computed(() => {
  let level = '';
  let label = '普通教师';
  let orgId = null;
  
  if (userStore.userInfo?.userType?.toLowerCase() === 'super_admin') {
    level = 'SUPER_ADMIN';
    label = '超级管理员';
    return { level, label, orgId };
  }
  
  if (!userStore.userInfo?.extraInfo) {
    return { level, label, orgId };
  }
  
  try {
    const extraInfo = JSON.parse(userStore.userInfo.extraInfo);
    level = extraInfo.admin_role || '';
    orgId = userStore.userInfo.orgId;
    
    switch (level) {
      case 'SCHOOL_ADMIN':
        label = '校级管理员';
        break;
      case 'DEPARTMENT_ADMIN':
        label = '院级管理员';
        break;
      case 'MAJOR_ADMIN':
        label = '系级管理员';
        break;
      case 'CLASS_ADMIN':
        label = '班级管理员';
        break;
    }
  } catch (e) {
    console.error('解析管理员信息失败', e);
  }
  
  return { level, label, orgId };
});

// 是否为校级管理员
const isSchoolAdmin = computed(() => {
  return ['SCHOOL_ADMIN', 'SUPER_ADMIN'].includes(adminInfo.value.level);
});

// 是否为超级管理员
const isSuperAdmin = computed(() => {
  return adminInfo.value.level === 'SUPER_ADMIN';
});

// 获取管理员角色级别数值，用于比较权限高低
const getAdminLevelValue = (adminRole) => {
  switch (adminRole) {
    case 'SUPER_ADMIN': return 4;
    case 'SCHOOL_ADMIN': return 3;
    case 'DEPARTMENT_ADMIN': return 2;
    case 'MAJOR_ADMIN': return 1;
    case 'CLASS_ADMIN': return 0;
    default: return -1;
  }
};

// 获取用户的管理员角色
const getAdminRole = (user) => {
  if (user.userType !== 'TEACHER' || !user.extraInfo) {
    return null;
  }
  
  try {
    const extraInfo = JSON.parse(user.extraInfo);
    return extraInfo.admin_role || null;
  } catch (e) {
    return null;
  }
};

// 获取管理员角色的显示标签
const getAdminRoleLabel = (user) => {
  const role = getAdminRole(user);
  if (!role) return '';
  
  switch (role) {
    case 'SCHOOL_ADMIN': return '校级管理员';
    case 'DEPARTMENT_ADMIN': return '院级管理员';
    case 'MAJOR_ADMIN': return '系级管理员';
    case 'CLASS_ADMIN': return '班级管理员';
    default: return '';
  }
};

// 判断是否应该显示某一列
const shouldShowColumn = (columnType) => {
  const level = adminInfo.value.level;
  
  // 超级管理员显示所有组织列
  if (level === 'SUPER_ADMIN') {
    return true;
  }
  
  // 校级管理员显示所有组织列
  if (level === 'SCHOOL_ADMIN') {
    return true;
  }
  
  // 院级管理员显示学院、专业和班级列
  if (level === 'DEPARTMENT_ADMIN') {
    return columnType === 'DEPARTMENT' || columnType === 'MAJOR' || columnType === 'CLASS';
  }
  
  // 系级管理员显示专业和班级列
  if (level === 'MAJOR_ADMIN') {
    return columnType === 'MAJOR' || columnType === 'CLASS';
  }
  
  // 班级管理员只显示班级列
  if (level === 'CLASS_ADMIN') {
    return columnType === 'CLASS';
  }
  
  // 普通教师显示所有列
  return true;
};

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true;
    let response;
    
    // 根据管理员级别决定查询方式
    if (adminInfo.value.level === 'SUPER_ADMIN') {
      // 超级管理员可以查看所有用户
      response = await request.get('/users');
    } else if (adminInfo.value.level) {
      // 其他管理员只能查看自己管理范围内的用户
      const userType = searchForm.value.userType || '';
      let url = `/users/org/${adminInfo.value.orgId}`;
      
      // 如果指定了用户类型，则添加到路径中
      if (userType) {
        url += `/type/${userType}`;
      } else {
        url += '/type'; // 不指定用户类型时使用不同的API路径
      }
      
      response = await request.get(url, {
        params: {
          includeSubOrgs: true  // 包含子组织的用户
        }
      });
    } else {
      // 普通教师无权查看用户列表
      userList.value = [];
      return;
    }
    
    if (response.code === 200) {
      // 过滤搜索条件
      userList.value = response.data.filter(user => {
        let match = true;
        
        // 按用户码搜索
        if (searchForm.value.usercode && !user.usercode.toLowerCase().includes(searchForm.value.usercode.toLowerCase())) {
          match = false;
        }
        
        // 按姓名搜索
        if (searchForm.value.fullName && !user.fullName.toLowerCase().includes(searchForm.value.fullName.toLowerCase())) {
          match = false;
        }
        
        return match;
      });
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 判断是否可以管理用户的管理员角色
const canManageAdminRole = (user) => {
  // 只有教师用户可以设置管理员角色
  if (user.userType !== 'TEACHER') {
    return false;
  }
  
  // 超级管理员可以管理所有角色
  if (adminInfo.value.level === 'SUPER_ADMIN') {
    return true;
  }
  
  // 获取当前管理员的权限级别
  const currentLevel = getAdminLevelValue(adminInfo.value.level);
  
  // 获取目标用户的管理员角色
  const userRole = getAdminRole(user);
  const userLevel = getAdminLevelValue(userRole);
  
  // 只能管理比自己权限级别低的用户
  return currentLevel > userLevel;
};

// 判断是否可以删除用户
const canDeleteUser = (user) => {
  // 超级管理员可以删除任何用户
  if (adminInfo.value.level === 'SUPER_ADMIN') {
    return true;
  }
  
  // 获取当前管理员的权限级别
  const currentLevel = getAdminLevelValue(adminInfo.value.level);
  
  // 如果目标是教师用户
  if (user.userType === 'TEACHER') {
    const userRole = getAdminRole(user);
    const userLevel = getAdminLevelValue(userRole);
    // 只能删除比自己权限级别低的教师
    return currentLevel > userLevel;
  }
  
  // 对于学生用户，任何级别的管理员都可以删除自己管理范围内的学生
  return true;
};

// 数据
const userList = ref([]);
const currentPage = ref(1);
const pageSize = ref(1000); // 设置一个很大的值，确保所有用户都显示在一页
const adminRoleDialogVisible = ref(false);
const loading = ref(false);
const adminRoleForm = ref({
  userId: null,
  fullName: '',
  adminRole: ''
});

// 表单
const searchForm = ref({
  usercode: '',
  fullName: '',
  userType: ''
});

// 方法
const handleSearch = () => {
  fetchUsers()
}

const resetSearch = () => {
  searchForm.value = {
    usercode: '',
    fullName: '',
    userType: ''
  }
  fetchUsers()
}

// 以下两个方法保留但不使用，使用 eslint-disable 注释来禁用相关警告
// eslint-disable-next-line no-unused-vars
const handlePageChange = (page) => {
  currentPage.value = page
  fetchUsers()
}

// eslint-disable-next-line no-unused-vars
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchUsers()
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？此操作不可恢复！', '警告', {
    type: 'warning',
    confirmButtonText: '确定删除',
    confirmButtonClass: 'el-button--danger',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      await request.delete(`/users/${row.userId}`);
      ElMessage.success('删除成功');
      fetchUsers();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
}

const handleAdminRole = (row) => {
  adminRoleDialogVisible.value = true;
  adminRoleForm.value = {
    userId: row.userId,
    fullName: row.fullName,
    adminRole: ''
  };
  
  // 如果用户有额外信息，解析管理员角色
  if (row.extraInfo) {
    try {
      const extraInfo = JSON.parse(row.extraInfo);
      adminRoleForm.value.adminRole = extraInfo.admin_role || '';
    } catch (e) {
      console.error('解析管理员信息失败', e);
    }
  }
}

const handleSubmitAdminRole = async () => {
  try {
    // 更新用户的管理员角色
    await request.put(`/users/${adminRoleForm.value.userId}/admin-role`, {
      adminRole: adminRoleForm.value.adminRole
    });
    
    ElMessage.success('设置管理员角色成功');
    adminRoleDialogVisible.value = false;
    fetchUsers();
  } catch (error) {
    ElMessage.error('设置管理员角色失败');
  }
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  margin-right: 15px;
}

.admin-tag {
  margin-right: auto;
}

.page-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.admin-role-tag {
  margin-top: 5px;
}
</style> 